Database tables are mean to be related to one another, for example, a blog post could have many comments this is called one-to-many relationship. in Laravel Eloquent makes managing and working with these relationships easily and support several types of relationships.
today's article will cover these following type of relationships:
One to One
one to one is the basic relation between databases. for example, a user might be associated with one phone.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Models\Phone');
}
}
we put Phone inside the User model, and that is how we define One to one relationships.
One to Many
One to Many is used to define relationships where a single model is related to any amount of other models. as we said earlier one blog post may have many comments.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
}
we use hasMany for one to many relationships.
Many to Many
this relation is slightly special if you compare it to the other. for example, the relation between the book and the author is called many to many relationships, because a book may have many authors and vice-versa.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
/**
* The book that belong to the authors.
*/
public function author()
{
return $this->belongsToMany('App\Models\Author');
}
}
we use the belongToMany Method for many to many relationships.
Inverted Relationship
for the inverted relationship between One to One and One to Many relationships, belongsTo method is used.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Models\Post');
}
}